package ltg.ibutton.core;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;

import ltg.ibutton.core.wrappers.FactoryWrapper;
import ltg.ibutton.core.wrappers.Wrapper;

public class Machine extends Observable implements Observer {
	private static Machine instance = null;
	private ArrayList<Reader> readers = null;
	
	private Machine() {
		readers = new ArrayList<Reader>();
		this.setup();
	}
	
	public static Machine getMachineInstance() {
		if(instance == null)
			instance = new Machine();
		return instance;
	}
	
	private void setup() {
		Wrapper wrp = FactoryWrapper.getWrapper();
		//this.readers.clear();
		for(Iterator<String> i = wrp.getReaders().iterator(); i.hasNext();) {
			Reader tmpReader = new Reader((String) i.next());
			tmpReader.addObserver(this);
			tmpReader.start();
			readers.add(tmpReader);
		}
	}
	
	public void stopReaderAutoUpdate(String readerid) throws Exception {
		boolean found = false;
		for(Iterator<Reader> i = readers.iterator(); i.hasNext();) {
			Reader tmp = i.next();
			if(readerid.equalsIgnoreCase(tmp.getId())) {
				tmp.stop();
				found = true;
			}
		}
		if(!found)
			throw new Exception("Reader " + readerid + " not found!");
	}
	
	public String toString() {
		String str = "";
		if(!readers.isEmpty())
			for(Iterator<Reader> i = readers.iterator(); i.hasNext();)
				str += ((Reader) i.next()).toString();
		return str;
	}
	
	public void update(Observable arg0, Object arg1) {
		System.err.println(arg0.toString());
		System.err.println("*************************************************");
		setChanged();
		notifyObservers(arg1);
	}
	
	public ArrayList<Reader> getAttachedReaders() {
		return readers;
	}
}
